//
//  ViewController.m
//  企业信息查询
//
//  Created by 梁中豪 on 16/4/6.
//  Copyright © 2016年 梁中豪. All rights reserved.
//

#import "ViewController.h"
#import "AppDelegate.h"
#import <BmobSDK/Bmob.h>
#import "News.h"
#import <CoreLocation/CoreLocation.h>

@interface ViewController ()<CLLocationManagerDelegate>
{
    CLLocationManager *locationManager;
}

- (IBAction)fuzhi:(id)sender;
- (IBAction)hotcall:(id)sender;
- (IBAction)live:(id)sender;
- (IBAction)water:(id)sender;
- (IBAction)public:(id)sender;
- (IBAction)all:(id)sender;
- (IBAction)truehotcall:(id)sender;

- (IBAction)loc:(id)sender;
@property (weak, nonatomic) IBOutlet UILabel *wether;
@property (weak, nonatomic) IBOutlet UIButton *local;


@end

@implementation ViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    //定位
    locationManager =[[CLLocationManager alloc] init];
    locationManager.delegate =self;
    locationManager.distanceFilter = kCLLocationAccuracyHundredMeters;
    [locationManager requestWhenInUseAuthorization];
    [locationManager startUpdatingLocation];
    
    NSURL *url = [NSURL URLWithString:@"http://wthrcdn.etouch.cn/weather_mini?citykey=101200101"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    NSURLSession *session =[NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *_Nullable data,NSURLResponse *_Nullable response,NSError *_Nullable error){
        
        NSString *dataStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        
        NSString *city = [dataStr substringWithRange:NSMakeRange([dataStr rangeOfString:@"city"].location+7, [dataStr rangeOfString:@"}}"].location-2-[dataStr rangeOfString:@"city"].location-7+1)];
        //截取前一部分的数据 提取
        NSString *datastr2 = [dataStr substringWithRange:NSMakeRange([dataStr rangeOfString:@"data"].location,185)];
        NSString *maxtemp = [datastr2 substringWithRange:NSMakeRange([datastr2 rangeOfString:@"high"].location+10, [datastr2 rangeOfString:@"type"].location-4-[datastr2 rangeOfString:@"high"].location-10+1)];
        NSString *mintemp = [datastr2 substringWithRange:NSMakeRange([datastr2 rangeOfString:@"low"].location+9, [datastr2 rangeOfString:@"date"].location-4-[datastr2 rangeOfString:@"low"].location-9+1)];
        NSString *type = [datastr2 substringWithRange:NSMakeRange([datastr2 rangeOfString:@"type"].location+7, [datastr2 rangeOfString:@"low"].location-4-[datastr2 rangeOfString:@"type"].location-7+1)];
        NSString *fengli = [datastr2 substringWithRange:NSMakeRange([datastr2 rangeOfString:@"fengli"].location+9, [datastr2 rangeOfString:@"high"].location-4-[datastr2 rangeOfString:@"fengli"].location-10+1)];        //NSString *nowdate = [[NSDate date] description];
        //获取当前日期，设置显示格式
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
        [dateFormatter setDateFormat:@"YYYY-MM-dd"];
        NSString *nowdate = [dateFormatter stringFromDate:[NSDate date]];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            _wether.text =  [NSString stringWithFormat:@"%@  %@  的天气状况是：%@  温度：%@ ~ %@  风力：%@" ,nowdate,city,type,mintemp,maxtemp,fengli];
        });
    }];
    [task resume];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (IBAction)fuzhi:(id)sender {
    AppDelegate *mydelegate=(AppDelegate*)[[UIApplication sharedApplication] delegate];
    mydelegate.CLNAME = @"canyin";
}

- (IBAction)hotcall:(id)sender {
    AppDelegate *mydelegate=(AppDelegate*)[[UIApplication sharedApplication] delegate];
    mydelegate.CLNAME = @"dangzheng";
}

- (IBAction)live:(id)sender {
    AppDelegate *mydelegate=(AppDelegate*)[[UIApplication sharedApplication] delegate];
    mydelegate.CLNAME = @"live";
}

- (IBAction)water:(id)sender {
    AppDelegate *mydelegate=(AppDelegate*)[[UIApplication sharedApplication] delegate];
    mydelegate.CLNAME = @"water";
}

- (IBAction)public:(id)sender {
    AppDelegate *mydelegate=(AppDelegate*)[[UIApplication sharedApplication] delegate];
    mydelegate.CLNAME = @"public";
}

- (IBAction)all:(id)sender {
    AppDelegate *mydelegate=(AppDelegate*)[[UIApplication sharedApplication] delegate];
    mydelegate.CLNAME = @"all";
}

- (IBAction)truehotcall:(id)sender {
//    AppDelegate *mydelegate=(AppDelegate*)[[UIApplication sharedApplication] delegate];
//    mydelegate.CLNAME = @"hotacall";
}

- (IBAction)loc:(id)sender {
    
    UIAlertController *city = [UIAlertController
                                         alertControllerWithTitle:@"定位功能"
                                         message:@"是否开启本地企业搜索？"
                                         preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *yesAction = [UIAlertAction actionWithTitle:@"开启"
                                                        style:UIAlertActionStyleCancel
                                                      handler:^(UIAlertAction *action){
                                                          [locationManager startUpdatingLocation];
                                                      }];
    UIAlertAction *noAction = [UIAlertAction actionWithTitle:@"关闭"
                                                       style:UIAlertActionStyleDefault
                                                     handler:^(UIAlertAction *action){
                                                         AppDelegate *mydelegate =(AppDelegate*)[[UIApplication sharedApplication] delegate];
                                                         mydelegate.place =@"null";
                                                     }];
    
    [city addAction:yesAction];
    [city addAction:noAction];
    
    //显示
    [self presentViewController:city animated:true completion:nil];
    
   
}

#pragma mark 跟踪定位代理方法，每次位置发生变化即会执行（只要定位到相应位置）
//可以通过模拟器设置一个虚拟位置，否则在模拟器中无法调用此方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    CLLocation *location=[locations firstObject];//取出第一个位置
    NSLog(@"%@",[NSString stringWithFormat:@"%lf,%lf",location.coordinate.longitude,location.coordinate.latitude]);
    //解析地址类
    CLGeocoder *geo =[[CLGeocoder alloc] init];
    CLLocation *location2=[[CLLocation alloc]initWithLatitude:location.coordinate.latitude longitude:location.coordinate.longitude];
    //开始解析 并回调block
    [geo reverseGeocodeLocation:location2 completionHandler:^(NSArray *placemarks,NSError *error){
        CLPlacemark *pl = [placemarks firstObject];
        NSLog(@"%@",pl.locality);
       //将定位到的城市赋值到按钮上
        [_local setTitle:pl.locality forState:UIControlStateNormal];
        
        AppDelegate *mydelegate =(AppDelegate*)[[UIApplication sharedApplication] delegate];
        mydelegate.place =pl.locality;
        
    }];
    
    //如果不需要实时定位，使用完即使关闭定位服务
    [locationManager stopUpdatingLocation];
    
}
@end
